import React, {PureComponent} from "react";
import {Icon, Popconfirm, Table} from "antd";
import {connect} from "react-redux";
import {paginationProps, tableProps} from "../../lib/ui";
import {del, query} from "./actions";
import {getCurrentOrganization, getLastFilter, getPrincipal} from "../../lib/identity";
import {Resizable} from 'react-resizable';
import {showEdit} from "./actions";
import {select} from "./actions";

const LAST_FILTER = "hisGhOrderReceivable";

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{enableUserSelectHack: false}}
        >
            <th {...restProps} />
        </Resizable>
    );
};

class List extends PureComponent {
    state = {
        columns: [
            {
                title: "所属机构",
                dataIndex: "organizationName",
                width: 80,
                ellipsis: true
            }, {
                title: "订舱号",
                dataIndex: "bookNo",
                width: 150,
                ellipsis: true,
                render: (text, record) => (
                    <a
                        onClick={() => {
                            this.handleShowEdit(record);
                        }}
                    >
                        {text}
                    </a>
                )
            }, {
                title: "客户",
                dataIndex: "clientName",
                width: 80,
                ellipsis: true
            }, {
                title: "业务类型",
                dataIndex: "businessType",
                width: 80,
                ellipsis: true
            }, {
                title: "计费方式",
                dataIndex: "calculateType",
                width: 80,
                ellipsis: true
            }, {
                title: "提货日期",
                dataIndex: "pickTime",
                width: 80,
                ellipsis: true
            }, {
                title: "发车日期",
                dataIndex: "sendTime",
                width: 80,
                ellipsis: true
            }, {
                title: "始发地",
                dataIndex: "startPlace",
                width: 80,
                ellipsis: true
            }, {
                title: "目的地",
                dataIndex: "endPlace",
                width: 80,
                ellipsis: true
            }, {
                title: "数量",
                dataIndex: "count",
                width: 80,
                ellipsis: true
            }, {
                title: "方数(m³)",
                dataIndex: "volume",
                width: 80,
                ellipsis: true
            }, {
                title: "毛重(KG)",
                dataIndex: "weight",
                width: 80,
                ellipsis: true
            }, {
                title: "重泡比",
                dataIndex: "pb",
                width: 80,
                ellipsis: true
            }, {
                title: "体积重(KG)",
                dataIndex: "volume2",
                width: 80,
                ellipsis: true
            }, {
                title: "提货车型",
                dataIndex: "pickType",
                width: 80,
                ellipsis: true
            }, {
                title: "提货线路",
                dataIndex: "pickLine",
                width: 80,
                ellipsis: true
            }, {
                title: "派送车型",
                dataIndex: "deliveryType",
                width: 80,
                ellipsis: true
            }, {
                title: "派送线路",
                dataIndex: "deliveryLine",
                width: 80,
                ellipsis: true
            }, {
                title: "车型备注",
                dataIndex: "carRemark",
                width: 80,
                ellipsis: true
            }, {
                title: "派送日期",
                dataIndex: "deliveryTime",
                width: 80,
                ellipsis: true
            }, {
                title: "备注",
                dataIndex: "remark",
                width: 80,
                ellipsis: true
            }, {
                title: "运输费(RMB)",
                dataIndex: "transportFee",
                width: 80,
                ellipsis: true
            }, {
                title: "提货费(RMB)",
                dataIndex: "pickFee",
                width: 80,
                ellipsis: true
            }, {
                title: "派送费(RMB)",
                dataIndex: "deliveryFee",
                width: 80,
                ellipsis: true
            }, {
                title: "合计（RMB)",
                dataIndex: "totalFee",
                width: 80,
                ellipsis: true
            }, {
                title: "",
                dataIndex: ""
            }
        ]
    };
    onPageChange = (page, pageSize) => {
        const {dispatch, filter} = this.props;
        dispatch(query({
            ...filter,
            page,
            "organizationId": getCurrentOrganization(),
            pageSize, "type": "IN"
        }));
    };

    handleShowEdit = row => {
        const {dispatch} = this.props;
        dispatch(showEdit(row));
    };

    handleDelete = id => {
        const {dispatch, page, pageSize, filter} = this.props;
        dispatch(del(id)).then(() => {
            dispatch(query({...filter, "organizationId": getCurrentOrganization(), page, pageSize, "type": "IN"}));
        });
    };


    componentWillMount() {
        const {dispatch, page, pageSize} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({page, pageSize, "organizationId": getCurrentOrganization(), ...fields, "type": "IN"}));
    };

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    handleSelectChange = (selectedRowKeys) => {
        const {dispatch} = this.props;
        dispatch(select(selectedRowKeys));
    };

    setRowClassName = (record) => {
        let className = '';
        // 订单锁定   #BEBEBE
        if (record.lockStatus === 1) {
            className = "table-color-lock";
        }
        return record.id === this.state.rowId ? 'clickRowStyl ' + className : className;
    }

    components = {
        header: {
            cell: ResizeableTitle,
        },
    };

    render() {
        const {
            page,
            pageSize,
            totalElements,
            selectedRowKeys,
            dataSource,
            loading,
        } = this.props;
        const columns = this.state.columns;
        if (getPrincipal().admin) {
            const found = columns.find(item => item.title === '功能');
            if (!found) {
                columns.push(
                    {
                        title: '功能',
                        dataIndex: '',
                        key: '',
                        width: 50,
                        align: 'center',
                        fixed: 'right',
                        render: (text, record) => <span>
                    <Popconfirm title="确定删除此记录?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDelete(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>,
                    }
                );
            }

        }
        const resizeColumns = columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        const rowSelection = {
            selectedRowKeys,
            columnWidth: '60px',
            onChange: this.handleSelectChange
        };
        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) =>
                this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };

        return (
            <Table
                {...tableProps}
                bordered
                columns={resizeColumns}
                components={this.components}
                scroll={{x: 1500, y: 'calc(100vh - 480px)'}}
                pagination={tablePagination}
                rowSelection={rowSelection}
                dataSource={dataSource}
                loading={loading}
                rowClassName={this.setRowClassName}
            />
        );
    }
}

const
    mapStateToProps = state => {
        return {
            ...state.hisGhOrderReceivable.list
        };
    };

export default connect(mapStateToProps)(List);
